package com.doris.lucene.servlet;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;

import com.doris.lucene.LuceneProperties;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * 在Web应用停止的时候更新配置文件
 * 
 * @author root
 *
 */
public class LuceneServletContextListener implements ServletContextListener {

	private static final Logger LOGGER = Logger.getLogger(LuceneServletContextListener.class);
	private static ThreadPoolExecutor pool;
	public static ThreadPoolExecutor getPool() {
		return pool;
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		LOGGER.info("应用关闭......");
		try {
			LuceneProperties.save();
		} catch (ConfigurationException e) {
			LOGGER.error("Lucene配置保存失败", e);
		}
		if (pool != null) {
			pool.shutdownNow();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		LOGGER.info("应用启动......");
		final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("DocumentParsePool-%d")
				.setDaemon(true).build();
		pool = new ThreadPoolExecutor(LuceneProperties.getCorePoolSize(), LuceneProperties.getMaximumPoolSize(), 100,
				TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
	}

}
